from __future__ import absolute_import
from forest.api import Command, get_tool

ETC_SYSCONFIG_HOSTNAME ='''NETWORKING=yes
HOSTNAME={}
'''

ETC_DHCP_DHCLIENT_CONF = '''send host-name = gethostname();
'''

class Hostname(Command):
    ''' Sets the hostname.

        Example::

            hostname: desired_hostname

        .. describe:: hostname

            A name for the host.
    '''
    __register__ = 'commands.setup.Hostname'

    requires_config = ['hostname']

    def run(self, config):
        hostname = config.get('hostname', False)

        if not hostname or not isinstance(hostname, basestring):
            raise Exception("setup.hostname should be string.")

        hostname_path = config.join_install_root('etc', 'sysconfig', 'network')
        get_tool('files.write')(hostname_path, ETC_SYSCONFIG_HOSTNAME.format(hostname))

        #OPTIONAL?
        dhclient_path = config.join_install_root('etc', 'dhcp', 'dhclient.conf')
        get_tool('files.write')(dhclient_path, ETC_DHCP_DHCLIENT_CONF, mode='w')
